package com.wyl.learn03;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.wyl.config.RabbitMqConfig;

import java.util.Scanner;

/**
 * 发布确认，单条消息同步发布确认
 */
public class Producer03_1 {
    public static final String TASK_QUEUE_NAME_CONFORM = "ack_queue_confirm";

    public static void main(String[] argv) throws Exception {
        //创建一个连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(RabbitMqConfig.IP);
        factory.setUsername(RabbitMqConfig.USERNAME);
        factory.setPassword(RabbitMqConfig.PASSWORD);
        //channel 实现了自动 close 接口 自动关闭 不需要显示关闭
        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {
            // 声明非持久化队列
            channel.queueDeclare(TASK_QUEUE_NAME_CONFORM, false, false, false,null);
            // 开启发布确认
            channel.confirmSelect();

            Scanner sc = new Scanner(System.in);
            System.out.println("请输入信息");
            while (sc.hasNext()) {
                String message = sc.nextLine();
                // 消息持久化
                // 发布非持久化消息
                channel.basicPublish("", TASK_QUEUE_NAME_CONFORM, null, message.getBytes("UTF-8"));
                // 同步阻塞式等待发布确认
                System.out.println("生产者发出消息" + message);
                if (channel.waitForConfirms()) {
                    System.out.println("消息发送成功");
                }
            }
        }
    }
}